import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { select, Store } from '@ngrx/store';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Subject } from 'rxjs';
import {  map, takeUntil } from 'rxjs/internal/operators';
import { SingerDetail, Song } from 'src/app/services/data-types/common.types';
import { SongService } from 'src/app/services/song.service';
import { AppStoreModule } from 'src/app/store';
import { BatchActionsService } from 'src/app/store/batch-actions.service';
import { getCurrentSong, getPlayer } from 'src/app/store/selectors/player.selector';
import { findIndex } from 'src/app/utils/array';

@Component({
  selector: 'app-singer-detail',
  templateUrl: './singer-detail.component.html',
  styleUrls: ['./singer-detail.component.less']
})
export class SingerDetailComponent implements OnInit, OnDestroy  {


  singerDetail!: SingerDetail;
  currentSong!: Song;
  currentIndex: number = -1;

  private destroy$ =  new Subject<void>();

  constructor(
    private route: ActivatedRoute,
    private store$: Store<AppStoreModule>,
    private batchActionServe: BatchActionsService,
    private songService: SongService,
    private nzMessageServe: NzMessageService,
  ) {
    this.route.data.pipe(map(res => res.singerDetail)).subscribe((res)=> {
      console.log(res)
      this.singerDetail = res
      this.listenCurrent()
    })
  }
  private listenCurrent(){
    this.store$
    .pipe(select(getPlayer), select(getCurrentSong), takeUntil(this.destroy$))
    .subscribe(song => {
      this.currentSong = song
      if(song){
        this.currentIndex = findIndex(this.singerDetail.hotSongs, song);
      }else{
        this.currentIndex = -1;
      }
    })
  }

  ngOnInit(): void {
  }
  // 歌单全部歌曲
  onAddSongs(songs: Song[], isPlay = false){
    this.songService.getSongList(songs)
    .subscribe(list => {
      if(list.length){
        if(isPlay){
          this.batchActionServe.selectPlayList({ list, index: 0 })
        }else{
          this.batchActionServe.insertSongs(list)
        }
      }else {
        this.nzMessageServe.create('warning' , '无url!')
      }
    })
  }

  // 添加一首歌曲
  onAddSong(song: Song, isPlay = false) {
    if(!this.currentSong || this.currentSong.id !== song.id){
      this.songService.getSongList(song)
      .subscribe(list => {
        if(list.length){
          this.batchActionServe.insertSong(list[0], isPlay)
        }else {
          this.nzMessageServe.create('warning' , '无url!')
        }
      })
    }
  }
  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
